package com.swdegao.iot.netty.utils;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

public class EdcodeMsg {
	public static byte starting_head = (byte) 0x80;
	public static byte command_type = (byte) 0x83;
	public byte registered_type = (byte) 0x81;
	public byte heartbeat_type = (byte) 0x82;
	public String imei;
	public String msg_body;
	static final byte[] g_hdr_id = { 126, 126, 126, 126 };
	public static ByteBuf getEdcodeMsg(String imei,String hexString){
		byte[] bit = ByteUtils.hexStringToBytes(hexString);
		byte[] msg = new byte[19 + bit.length +3];
        msg[0] = starting_head;
        //byte hDate = (byte)(msg.length / 256);
	      //byte lDate = (byte)(msg.length % 256);
        msg[1] = (byte)Integer.parseInt(msg.length+"", 16);
        msg[2] = 0;
        msg[3] = command_type;
        byte[] imei_ = imei.getBytes();
        System.arraycopy(imei_, 0, msg, 4, 15);//类型、imie

        System.arraycopy(bit, 0, msg, 19, bit.length);

        msg[msg.length - 3] = getTotalbyte(msg);
        msg[msg.length - 2] = 0x0d;
        msg[msg.length - 1] = 0x0a;
        return Unpooled.wrappedBuffer(msg);
	}
	  public static byte getTotalbyte(byte[] bit)
	  {
	    int temp = 0;
	    for (int i = 0; i < bit.length; i++) {
	      temp = bit[i] + temp;
	    }
	    byte rein = (byte)(temp & 0xFF);
	    return rein;
	  }



	    public static int byteToInt(byte[] bytes) {
	        int num = bytes[1] & 0xFF;
	        num |= bytes[0] << 8 & 0xFF00;
	        return num;
	      }

}
